package host

import (
	"github.com/gin-gonic/gin"
	"github.com/infraboard/mcube/http/request"
	"go-step/s9_cmdb/api/models"
	"go-step/s9_cmdb/api/service/host"
	"go-step/s9_cmdb/api/tools/response"
	"strconv"
)

func QueryHost(c *gin.Context) {
	//query := host.NewQueryHostRequestFromHTTP(c.Request)
	set, err := host.QueryHost()
	if err != nil {
		response.Failed(c.Writer, err)
		return
	}
	response.Success(c.Writer, set)
}

func CreateHost(c *gin.Context) {
	ins := &models.Host{}
	if err := request.GetDataFromRequest(c.Request, ins); err != nil {
		response.Failed(c.Writer, err)
		return
	}

	err := host.SaveHost(c.Request.Context(), ins)
	if err != nil {
		response.Failed(c.Writer, err)
		return
	}
	response.Success(c.Writer, "创建成功")
}

func DeleteHost(c *gin.Context) {
	query := host.NewQueryHostRequestFromHTTP(c.Request)
	set, err := host.DeleteHost(c.Request.Context(), query)
	if err != nil {
		response.Failed(c.Writer, err)
		return
	}
	response.Success(c.Writer, set)
}

func PutHost(c *gin.Context) {
	sid, ok := c.Params.Get("id")
	id, err := strconv.Atoi(sid)
	if !ok || err != nil {
		c.JSON(400, gin.H{"msg": "id must not null"})
	}
	req := &models.Host{Id: id}

	if err := request.GetDataFromRequest(c.Request, req); err != nil {
		response.Failed(c.Writer, err)
		return
	}

	ins, err := host.UpdateHost(c.Request.Context(), req)
	if err != nil {
		response.Failed(c.Writer, err)
		return
	}

	response.Success(c.Writer, ins)
}
